from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.core.paginator import Paginator

from .models import Film
from .serializers import FilmListSerializer


# Create your views here.


@api_view(['GET'])
def film_list(request):
    """影票列表接口 - 支持分页和筛选"""
    try:
        # 获取查询参数
        pagenum = int(request.GET.get('pagenum', 1))
        pagesize = int(request.GET.get('pagesize', 10))
        area = request.GET.get('area', '')
        film_type = request.GET.get('type', '')
        cinema_id = request.GET.get('cinema_id')
        category = request.GET.get('category')
        search = request.GET.get('search', '')

        # 构建查询集
        films = Film.objects.all()

        # 按影院筛选
        if cinema_id:
            films = films.filter(cinema__store_id=cinema_id)

        # 按区域筛选
        # if area and area != '0':
        #     films = films.filter(cinema__area_id=int(area))

        # 按电影类型筛选
        if film_type:
            films = films.filter(type=int(film_type))

        # 按分类筛选
        if category:
            films = films.filter(category__icontains=category)

        # 按名称搜索
        if search:
            films = films.filter(name__icontains=search)

        # 分页处理
        paginator = Paginator(films, pagesize)
        try:
            page_obj = paginator.page(pagenum)
        except:
            page_obj = paginator.page(1)

        # 序列化数据
        serializer = FilmListSerializer(page_obj.object_list, many=True)

        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': {
                'total': films.count(),
                # 'pagenum': pagenum,
                # 'pagesize': pagesize,
                # 'total_pages': paginator.num_pages,
                'list': serializer.data
            }
        })

    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def swiper_list(request):
    """首页轮播图数据"""
    try:
        # 构建查询集
        films = Film.objects.all()

        films = films.filter(recommend=1)

        # 序列化数据
        serializer = FilmListSerializer(films, many=True)

        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': serializer.data
        })
    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# @api_view(['GET'])
# def film_by_cinema(request, cinema_id):
#     """根据影院获取影票列表"""
#     try:
#         films = Film.objects.filter(cinema__store_id=cinema_id)
#
#         serializer = FilmListSerializer(films, many=True)
#
#         return Response({
#             'state': 200,
#             'msg': '操作成功',
#             'data': {
#                 'total': films.count(),
#                 'list': serializer.data
#             }
#         })
#
#     except Exception as e:
#         return Response({
#             'state': 500,
#             'msg': f'操作失败: {str(e)}',
#             'data': None
#         }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def film_detail(request, film_id):
    """影票列表接口 - 支持分页和筛选"""
    try:
        # 构建查询集
        films = Film.objects.all()

        films = films.filter(id=film_id)

        # 序列化数据
        serializer = FilmListSerializer(films, many=True)

        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': serializer.data[0]
        })

    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def film_search(request):
    try:
        params_dict = request.GET.dict()

        key = params_dict.get('key')
        # 构建查询集
        films = Film.objects.all()

        films = films.filter(name__contains=key)
        # 序列化数据
        serializer = FilmListSerializer(films, many=True)
        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': serializer.data
        })
    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
